<script setup>
import { useAddEditHook } from '@/hooks/crud/index.js'
import { useColumnsDict, useCommonConfig } from './hook.js'
import { useFormConfigHook } from '@/hooks/usePlusConfigHook.js'
import { listDept, listDeptExcludeChild } from '@/api/system/dept.js'
const { proxy,  primaryKey,apiFn, moduleName } = useCommonConfig()
const emit = defineEmits(['refreshList'])

// 表单初始化数据
const initForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0'
}
const rules = {
  parentId: [{ required: true, message: '上级部门不能为空', trigger: 'change' }],
  deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
}

const deptOptions = ref([])
// 钩子函数
const handlerConfig = {
  beforeOpenFn:(data)=>{
    if(data.addParentId>=0){
      listDept().then((response) => {
        deptOptions.value = proxy.handleTree(response.data, 'deptId')
      })
      gFormData.value.parentId = data.addParentId
    }else{
      listDeptExcludeChild(data[primaryKey]).then((response) => {
        deptOptions.value = proxy.handleTree(response.data, primaryKey)
      })
    }
  },
  beforeInfoFn: (reqData) => {
    return reqData[[primaryKey]]
  },
  afterInfoFn: (resData) => {
    return resData
  },
  beforeSubmitFn: (reqData) => {
    return reqData
  },
  afterSubmitFn: (resData) => {
    emit('refreshList')
    return resData
  },
  beforeCloseFn: () => true,
  afterCloseFn: () => {}
}

const { gOpen, gAllExposeOption,gVisible,gFormInstance,gFormData, gIsEdit  } = useAddEditHook({
  moduleName,
  primaryKey,
  initForm,
  rules,
  apiFnConfig:apiFn.apiFnConfig,
  handlerConfig
})

const { gDialogConfig,  gFormConfig} = useFormConfigHook(gAllExposeOption,{
  dialogConfig:{
    width: 700
  },
  formConfig:{
    labelWidth: 100,
    colProps: {
      span: 12
    }
  }
});
const {  dictData,  columns, } = useColumnsDict(true,gFormData);
// 暴露
defineExpose({ gOpen })
</script>
<template>
  <PlusDialog v-model="gVisible" v-bind="gDialogConfig">
    <PlusForm ref="gFormInstance" v-model="gFormData" :columns="columns" v-bind="gFormConfig">
      <template #plus-field-parentId>
        <el-tree-select
          v-model="gFormData.parentId"
          :data="deptOptions"
          :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
          value-key="deptId"
          placeholder="选择上级部门"
          check-strictly
        />
      </template>
    </PlusForm>
  </PlusDialog>
</template>
<style lang="scss" scoped></style>
